const qs = require('querystring');

const md5 = require('md5');

const httpUtil = require('../utils/httpUtils');

const err = require('../common/err');
const url = require('../common/url')['youdaofanyi'];
const config = require('../common/youdaoConfig');

function fanyi(q, callback) {
  if (!q) {
    console.error('[Error] youdaoService.js - fanyi -- parameter \'q\' is requied!');
    callback(err.missingParameter, null);
    return;
  } else if (typeof q !== 'string') {
    console.error('[Error] youdaoService.js - fanyi -- first parameter must be a string!');
    callback(err.wrongTypeParameter, null);
    return;
  }

  const salt = `${Math.random()}`;
  const sign = md5(config.appKey + q + salt + config.key).toUpperCase();
  const data = {
    q: q,
    from: config.from,
    to: config.to,
    appKey: config.appKey,
    salt: salt,
    sign: sign,
    ext: config.ext
  }
  console.log(qs.stringify(data));

  httpUtil.post(url, qs.stringify(data), function cb(err, result) {
    if (err) {
      console.error(`[Error] youdaoService.js - fanyi -- ${err.msg}`);
      callback(err.getDataFail, null);
      return;
    }

    console.log(result);
    callback(null, result);
  });
}

module.exports = {
  fanyi: fanyi
}